<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo">
          <el-icon size="50" color="#409eff"><School /></el-icon>
        </div>
        <h1 class="title">在线考试系统</h1>
        <p class="subtitle">欢迎登录</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <!-- 验证码 -->
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              size="large"
              style="flex: 1"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaUrl" alt="验证码" v-if="captchaUrl" />
              <span v-else>点击获取</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 快速登录 -->
      <div class="quick-login">
        <el-divider>快速登录</el-divider>
        <div class="quick-login-buttons">
          <el-button 
            type="danger" 
            size="small" 
            @click="quickLogin('admin', '123456')"
            :loading="loading"
          >
            管理员登录
          </el-button>
          <el-button 
            type="warning" 
            size="small" 
            @click="quickLogin('teacher', '123456')"
            :loading="loading"
          >
            教师登录
          </el-button>
          <el-button 
            type="success" 
            size="small" 
            @click="quickLogin('student', '123456')"
            :loading="loading"
          >
            学生登录
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import request from '@/utils/request'

const router = useRouter()
const authStore = useAuthStore()

const loginFormRef = ref()
const loading = ref(false)
const rememberMe = ref(false)
const captchaUrl = ref('')
const captchaKey = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

onMounted(() => {
  refreshCaptcha()
})

const refreshCaptcha = async () => {
  try {
    // 尝试从后端获取验证码
    try {
      const response = await request.get('/captcha/image')
      if (response.data && response.data.success && response.data.key) {
        captchaKey.value = response.data.key
        captchaUrl.value = `data:image/png;base64,${response.data.image}`
        return
      }
    } catch (error) {
      console.log('Backend captcha not available, using mock captcha:', error)
    }
    
    // 后端不可用时使用模拟验证码
    const mockCaptcha = Math.random().toString(36).substring(2, 8).toUpperCase()
    captchaKey.value = 'mock-key'
    
    // 创建验证码图片
    const canvas = document.createElement('canvas')
    canvas.width = 120
    canvas.height = 40
    const ctx = canvas.getContext('2d')
    if (ctx) {
      // 背景
      ctx.fillStyle = '#f0f0f0'
      ctx.fillRect(0, 0, 120, 40)
      
      // 添加干扰线
      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = `hsl(${Math.random() * 360}, 50%, 50%)`
        ctx.beginPath()
        ctx.moveTo(Math.random() * 120, Math.random() * 40)
        ctx.lineTo(Math.random() * 120, Math.random() * 40)
        ctx.stroke()
      }
      
      // 验证码文字
      ctx.fillStyle = '#333'
      ctx.font = 'bold 18px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(mockCaptcha, 60, 25)
    }
    
    captchaUrl.value = canvas.toDataURL()
    // 存储正确答案用于验证
    ;(window as any).mockCaptchaAnswer = mockCaptcha
  } catch (error) {
    console.error('生成验证码失败:', error)
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    try {
      console.log('[Login] 开始登录...')
      
      // 构建登录请求数据
      const credentials = {
        username: loginForm.username,
        password: loginForm.password,
        captcha: loginForm.captcha,
        captchaKey: captchaKey.value
      }
      
      // 使用真实的登录API
      const response = await request.post('/auth/login', credentials)
      
      if (response.data && response.data.token && response.data.user) {
        // 保存token和用户信息
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        
        authStore.token = response.data.token
        authStore.user = response.data.user
        
        console.log('[Login] 登录成功，用户信息:', authStore.user)
        console.log('[Login] Token:', authStore.token)
        
        ElMessage.success('登录成功')
        
        // 登录成功后立即跳转到主页面，让MainLayout加载菜单
        router.replace('/dashboard')
      } else {
        ElMessage.error('登录响应格式错误')
      }
      
    } catch (error: any) {
      console.error('登录失败:', error)
      ElMessage.error(error.response?.data?.message || '登录失败，请稍后重试')
      refreshCaptcha() // 刷新验证码
    }
    
  } catch (error) {
    console.error('表单验证错误:', error)
  } finally {
    loading.value = false
  }
}

const quickLogin = (username: string, password: string) => {
  loginForm.username = username
  loginForm.password = password
  loginForm.captcha = 'demo' // 演示账号跳过验证码
  handleLogin()
}

// 页面加载时检查记住我功能
onMounted(() => {
  const savedUsername = localStorage.getItem('savedUsername')
  const rememberMeFlag = localStorage.getItem('rememberMe')
  
  if (rememberMeFlag === 'true' && savedUsername) {
    loginForm.username = savedUsername
    rememberMe.value = true
  }
})
</script>

<style scoped>
.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.login-box {
  position: relative;
  z-index: 10;
  width: 420px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  margin-bottom: 20px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
  margin: 0 0 10px 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  transition: all 0.3s;
}

.captcha-image:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 3px;
}

.captcha-image span {
  font-size: 12px;
  color: #909399;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 8px;
  transition: all 0.3s;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.quick-login {
  margin-top: 20px;
}

.quick-login-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.quick-login-buttons .el-button {
  flex: 1;
  min-width: 100px;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 10%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.7;
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
    opacity: 0.3;
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 30px 20px;
    margin: 20px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .quick-login-buttons {
    flex-direction: column;
  }
  
  .quick-login-buttons .el-button {
    width: 100%;
  }
}

/* 表单项样式优化 */
.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.login-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 复选框和链接样式 */
.login-options :deep(.el-checkbox__label) {
  color: #606266;
}

.login-options :deep(.el-link) {
  font-size: 14px;
}
</style>